﻿#include <stdio.h>

static int flip(int n) {
    return n ^ 1;
}

/**
 * n是非负数，返回1；n是负数，返回0
 */
static int sign(int n) {
    return flip((n >> 31) & 1);
}

static int add(int a, int b) {
    int sum = a;
    while (b != 0) {
        sum = a ^ b;
        b = (a & b) << 1;
        a = sum;
    }

    return sum;
}

static int negNum(int n) {
    return add(~n, 1);
}

static int minus(int a, int b) {
    return add(a, negNum(b));
}

static int multi(int a, int b) {
    bool samePostive = sign(a) == sign(b);
    a = sign(a) ? a : negNum(a);
    b = sign(b) ? b : negNum(b);

    int res = 0;
    while (b != 0) {
        if ((b & 1) != 0) {
            res = add(res, a);
        }

        a <<= 1;
        b >>= 1;
    }

    return samePostive ? res : negNum(res);
}

static int divide(int a, int b) {
    bool samePostive = sign(a) == sign(b);
    a = sign(a) ? a : negNum(a);
    b = sign(b) ? b : negNum(b);

    int res = 0;
    for (int i = 31; i > -1; i = minus(i, 1)) {
        if ((a >> i) >= b) {
            res |= (1 << i);
            a = minus(a, b << i);
        }
    }

    return samePostive ? res : negNum(res);
}

int main_BitOperation()
{
    int res = divide(99999, 4);
    printf("%d\n", res);
    return 0;
}